//
//  BLViewController.m
//  ITC_iOS
//
//  Created by iBenz on 2018/8/25.
//  Copyright © 2018年 Benz.L. All rights reserved.
//

#import "BLViewController.h"
#import <objc/runtime.h>

//#import "UINavigationController+FDFullscreenPopGesture.h"

@interface BLViewController ()<UIGestureRecognizerDelegate>
@end

@implementation BLViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.needToHideNavigationBar = NO;
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"");
}
/*
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    UIViewController *vc = self.navigationController.visibleViewController;
    
    if ([vc isKindOfClass:NSClassFromString(@"BLViewController")]) {
        BLViewController *nextVC = (BLViewController *)vc;
        if (nextVC.parentViewController && [nextVC.parentViewController isKindOfClass:[UINavigationController class]]) {
            BOOL originNavBarHidden = nextVC.navigationController.navigationBarHidden;
            if (originNavBarHidden != nextVC.needToHideNavigationBar) {
                // 从无到有
                // FIXME: setNavigationBarHidden:NO 不能放在viewdidappear中，左滑返回动作不完成时，再通过返回按钮返回后，进入二级页面navbar不会改变
                [nextVC.navigationController setNavigationBarHidden:nextVC.needToHideNavigationBar animated:YES];
            }
        }
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setNeedsStatusBarAppearanceUpdate];
    
    if (self.parentViewController && [self.parentViewController isKindOfClass:[UINavigationController class]]) {
        BOOL originNavBarHidden = self.navigationController.navigationBarHidden;
        if (originNavBarHidden != self.needToHideNavigationBar) {
            // 从有到无
            // 系统bug：这里navigation bar 必须animated设yes，否则从有到无时左滑返回动作不完成时，即滑动一点然后取消返回，然后再进去下一级有一样有navbar的页面时，navbarUI异常
            [self.navigationController setNavigationBarHidden:self.needToHideNavigationBar animated:YES];
        }
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
*/
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    if (self.navigationController && [[self.navigationController viewControllers] count] > 1) {
        self.navigationItem.leftBarButtonItem = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(0, 0, 60, 40);
            button.exclusiveTouch = YES;
            [button setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
            //button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 48);
            button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            button.titleLabel.font = [UIFont systemFontOfSize:14];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            //[button setTitle:@" 返回" forState:UIControlStateNormal];
            [button addTarget:self action:@selector(popNavigationViewController) forControlEvents:UIControlEventTouchUpInside];
            UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
            item;
        });
        
        //为了让titleView居中。titleview的位置取决与leftBarButtonItem 和 rightBarButtonItem
        self.navigationItem.rightBarButtonItem = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(0, 0, 40, 40);
            button.enabled = NO;
            button.titleLabel.font = [UIFont systemFontOfSize:14];
            button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
            UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
            item;
        });
        
    } else {
        UIView *cleanView = [[UIView alloc] init];
        cleanView.backgroundColor = [UIColor clearColor];
        UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cleanView];
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    }
    
    //self.fd_prefersNavigationBarHidden = _needToHideNavigationBar;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (UIButton *)leftBarButton {
    UIBarButtonItem *item = self.navigationItem.leftBarButtonItem;
    UIButton *btn = (UIButton *)item.customView;
    if (btn && [btn isKindOfClass:UIButton.class]) {
        return btn;
    }
    return nil;
}
- (UIButton *)rightBarButton {
    UIBarButtonItem *item = self.navigationItem.rightBarButtonItem;
    if (!item) {
        item = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(0, 0, 40, 40);
            button.enabled = NO;
            button.titleLabel.font = [UIFont systemFontOfSize:14];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
            UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
            item;
        });
        self.navigationItem.rightBarButtonItem = item;
    }
    UIButton *btn = (UIButton *)item.customView;
    if (btn && [btn isKindOfClass:UIButton.class]) {
        return btn;
    }
    return nil;
    
//    UIBarButtonItem *item = self.navigationItem.rightBarButtonItem;
//    UIButton *btn = (UIButton *)item.customView;
//    if (btn && [btn isKindOfClass:UIButton.class]) {
//        return btn;
//    }
//    return nil;
}

- (void)popNavigationViewController {
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)fd_prefersNavigationBarHidden {
    return self.needToHideNavigationBar;
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

NSString const *kAppRunCycleKey = @"kAppRunCycleKey";
- (void)enableApplicationRunCycleEvents:(BOOL)enable {
    BOOL isEnable = [objc_getAssociatedObject(self, &kAppRunCycleKey) boolValue];
    if (enable) {
        if (!isEnable) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationCycleNotification:) name:UIApplicationDidEnterBackgroundNotification object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationCycleNotification:) name:UIApplicationWillEnterForegroundNotification object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationCycleNotification:) name:UIApplicationDidBecomeActiveNotification object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationCycleNotification:) name:UIApplicationWillResignActiveNotification object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationCycleNotification:) name:UIApplicationWillTerminateNotification object:nil];
        }
    }
    else {
        if (isEnable) {
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];
        }
    }
    objc_setAssociatedObject(self, &kAppRunCycleKey, @(enable), OBJC_ASSOCIATION_RETAIN);
}

- (void)applicationCycleNotification:(NSNotification *)notification {
    UIApplication *app = notification.object;
    if (notification.name==UIApplicationDidEnterBackgroundNotification) {
        [self applicationDidEnterBackground:app];
    }
    else if (notification.name==UIApplicationWillEnterForegroundNotification) {
        [self applicationWillEnterForeground:app];
    }
    else if (notification.name==UIApplicationDidBecomeActiveNotification) {
        [self applicationDidBecomeActive:app];
    }
    else if (notification.name==UIApplicationWillResignActiveNotification) {
        [self applicationWillResignActive:app];
    }
    else if (notification.name==UIApplicationWillTerminateNotification) {
        [self applicationWillTerminate:app];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application;{}
- (void)applicationDidEnterBackground:(UIApplication *)application;{}
- (void)applicationWillEnterForeground:(UIApplication *)application;{}
- (void)applicationDidBecomeActive:(UIApplication *)application;{}
- (void)applicationWillTerminate:(UIApplication *)application;{}
/*
#pragma mark - UIScreenEdgePanGestureRecognizer

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if (self.navigationController.viewControllers.count <= 1){
        return NO;
    }
    return YES;
}

- (UIScreenEdgePanGestureRecognizer *)screenEdgePanGestureRecognizer
{
    UIScreenEdgePanGestureRecognizer *screenEdgePanGestureRecognizer = nil;
    if (self.navigationController.view.gestureRecognizers.count > 0) {
        for (UIGestureRecognizer *recognizer in self.navigationController.view.gestureRecognizers) {
            if ([recognizer isKindOfClass:[UIScreenEdgePanGestureRecognizer class]]) {
                screenEdgePanGestureRecognizer = (UIScreenEdgePanGestureRecognizer *)recognizer;
                break;
            }
        }
    }
    
    return screenEdgePanGestureRecognizer;
}
*/
@end
